#!/usr/bin/env python3
"""
前端菜单生成Agent
自动根据菜单数据结构生成各种前端框架的菜单组件代码
"""

import json
import os
from typing import Dict, List, Any, Optional
from dataclasses import dataclass
from enum import Enum

class FrameworkType(Enum):
    VUE_ELEMENT = "vue_element"
    REACT_ANTD = "react_antd"
    VANILLA_JS = "vanilla_js"

@dataclass
class MenuGenerationConfig:
    """菜单生成配置"""
    framework: FrameworkType
    output_dir: str
    component_name: str = "MenuComponent"
    theme: str = "default"
    enable_icons: bool = True
    enable_permissions: bool = False
    collapse_support: bool = True
    search_support: bool = False

class MenuAgent:
    """前端菜单生成Agent"""
    
    def __init__(self, config: MenuGenerationConfig):
        self.config = config
        self.icon_map = {
            '移动执法': 'Mobile',
            '污染源档案': 'FolderOpen', 
            '企业环境健康码': 'QrCode',
            '秸秆网格化管理': 'Grid3x3',
            '装备调度': 'Tool',
            '系统管理': 'Setting',
            '管理': 'Setting',
            '数据': 'BarChart',
            '分析': 'LineChart',
            '执法': 'Shield',
            '监管': 'Eye',
            '档案': 'Archive',
            '信息': 'Info'
        }
    
    def load_menu_data(self, data_dir: str) -> Dict[str, Any]:
        """加载菜单数据和路由数据"""
        menu_data = {}
        
        # 加载一级菜单
        first_level_file = os.path.join(data_dir, "first_level_menus.json")
        if os.path.exists(first_level_file):
            with open(first_level_file, 'r', encoding='utf-8') as f:
                menu_data['first_level'] = json.load(f)
        
        # 加载各菜单组
        menu_data['groups'] = []
        for i in range(1, 7):
            group_file = os.path.join(data_dir, f"menu_group_{i}.json")
            if os.path.exists(group_file):
                with open(group_file, 'r', encoding='utf-8') as f:
                    menu_data['groups'].append(json.load(f))
        
        # 加载路由数据
        router_file = os.path.join(data_dir, "router.js")
        if os.path.exists(router_file):
            menu_data['routes'] = self.load_router_data(router_file)
            print(f"✓ 加载路由数据: {len(menu_data['routes'])} 条路由")
        
        return menu_data
    
    def load_router_data(self, router_file: str) -> List[Dict[str, Any]]:
        """加载并解析路由数据"""
        try:
            with open(router_file, 'r', encoding='utf-8') as f:
                content = f.read()
            
            return self.parse_router_js(content)
        except Exception as e:
            print(f"❌ 加载路由数据失败: {e}")
            return []
    
    def parse_router_js(self, content: str) -> List[Dict[str, Any]]:
        """解析JavaScript路由文件"""
        import re
        routes = []
        
        # 更完整的路由匹配模式
        route_patterns = [
            # 标准路由模式: { path: "...", name: "...", component: () => import("...") }
            r'\{\s*path:\s*["\']([^"\']+)["\'],\s*name:\s*["\']([^"\']+)["\'],\s*component:\s*\(\)\s*=>\s*import\(["\']([^"\']+)["\']',
            # 简化路由模式
            r'path:\s*["\']([^"\']+)["\'][^}]*name:\s*["\']([^"\']+)["\'][^}]*component:[^"\']*["\']([^"\']+)["\']'
        ]
        
        for pattern in route_patterns:
            matches = re.findall(pattern, content, re.MULTILINE | re.DOTALL)
            
            for match in matches:
                if len(match) >= 3:
                    path, name, component = match[:3]
                    routes.append({
                        'path': path,
                        'name': name,
                        'component': component.replace('@/', 'src/'),
                        'componentName': self.extract_component_name(component)
                    })
        
        return routes
    
    def extract_component_name(self, component_path: str) -> str:
        """从组件路径提取组件名称"""
        # 提取文件名（不含扩展名）
        filename = component_path.split('/')[-1]
        if '.' in filename:
            filename = filename.split('.')[0]
        
        # 转换为PascalCase
        return ''.join(word.capitalize() for word in filename.split('_'))
    
    def match_routes_to_menu(self, menu_data: List[Dict[str, Any]], routes: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """将路由信息匹配到菜单项中"""
        route_map = {route['path']: route for route in routes}
        
        def enhance_menu_item(item):
            if isinstance(item, dict):
                # 为菜单项添加路由信息
                path = item.get('path', '')
                if path in route_map:
                    item['route'] = route_map[path]
                
                # 递归处理子菜单
                if 'children' in item and isinstance(item['children'], list):
                    if item['children'] and isinstance(item['children'][0], dict):
                        item['children'] = [enhance_menu_item(child) for child in item['children']]
            
            return item
        
        return [enhance_menu_item(item) for item in menu_data]
    
    def get_icon_name(self, menu_name: str) -> str:
        """根据菜单名称获取图标"""
        # 直接匹配
        if menu_name in self.icon_map:
            return self.icon_map[menu_name]
        
        # 关键词匹配
        for keyword, icon in self.icon_map.items():
            if keyword in menu_name:
                return icon
        
        return 'Menu'  # 默认图标
    
    def generate_vue_element_component(self, menu_data: Dict[str, Any]) -> str:
        """生成Vue + Element Plus菜单组件"""
        template = '''<template>
  <div class="menu-container">
    <el-menu
      :default-active="activeMenu"
      mode="vertical"
      :collapse="isCollapse"
      @select="handleMenuSelect"
      class="menu-wrapper"
    >
      <template v-for="item in menuData" :key="item.id">
        <menu-item :menu-item="item" />
      </template>
    </el-menu>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import MenuItem from './MenuItem.vue'

interface MenuItemType {
  id: number
  name: string
  path: string
  children: MenuItemType[] | string[]
  icon?: string
}

const props = defineProps<{
  menuData: MenuItemType[]
  collapse?: boolean
}>()

const router = useRouter()
const route = useRoute()

const activeMenu = ref('')
const isCollapse = computed(() => props.collapse || false)

const handleMenuSelect = (index: string, indexPath: string[]) => {
  if (index && index !== '#') {
    router.push(index)
  }
}

onMounted(() => {
  activeMenu.value = route.path
})
</script>

<style scoped>
.menu-container {
  height: 100%;
  border-right: 1px solid #e6e6e6;
}

.menu-wrapper {
  height: 100%;
  border-right: none;
}
</style>'''

        menu_item_template = '''<template>
  <div>
    <!-- 有子菜单的情况 -->
    <el-sub-menu 
      v-if="hasChildren" 
      :index="menuItem.id.toString()"
      :key="menuItem.id"
    >
      <template #title>
        <el-icon v-if="showIcon">
          <component :is="iconComponent" />
        </el-icon>
        <span>{{ menuItem.name }}</span>
      </template>
      
      <template v-for="child in menuItem.children" :key="getChildKey(child)">
        <!-- 递归渲染对象类型的子菜单 -->
        <menu-item 
          v-if="typeof child === 'object'" 
          :menu-item="child" 
        />
        <!-- 渲染字符串类型的子菜单 -->
        <el-menu-item 
          v-else 
          :index="`${menuItem.path}/${child}`"
          class="string-menu-item"
        >
          <span>{{ child }}</span>
        </el-menu-item>
      </template>
    </el-sub-menu>
    
    <!-- 无子菜单的情况 -->
    <el-menu-item 
      v-else 
      :index="menuItem.path || '#'" 
      :key="menuItem.id"
    >
      <el-icon v-if="showIcon">
        <component :is="iconComponent" />
      </el-icon>
      <span>{{ menuItem.name }}</span>
    </el-menu-item>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import * as ElementPlusIcons from '@element-plus/icons-vue'

interface MenuItemType {
  id: number
  name: string
  path: string
  children: MenuItemType[] | string[]
  icon?: string
}

const props = defineProps<{
  menuItem: MenuItemType
  showIcon?: boolean
}>()

const hasChildren = computed(() => 
  props.menuItem.children && props.menuItem.children.length > 0
)

const showIcon = computed(() => props.showIcon !== false)

const iconComponent = computed(() => {
  const iconName = getIconName(props.menuItem.name)
  return (ElementPlusIcons as any)[iconName] || ElementPlusIcons.Menu
})

const getIconName = (menuName: string): string => {
  const iconMap: Record<string, string> = {
    '移动执法': 'Cellphone',
    '污染源档案': 'FolderOpened',
    '企业环境健康码': 'Stamp',
    '秸秆网格化管理': 'Grid',
    '装备调度': 'Tools',
    '系统管理': 'Setting'
  }
  
  return iconMap[menuName] || 'Menu'
}

const getChildKey = (child: MenuItemType | string): string => {
  return typeof child === 'object' ? child.id.toString() : child
}
</script>

<style scoped>
.string-menu-item {
  padding-left: 60px !important;
}
</style>'''

        return {
            'MenuComponent.vue': template,
            'MenuItem.vue': menu_item_template
        }
    
    def generate_react_antd_component(self, menu_data: Dict[str, Any]) -> str:
        """生成React + Ant Design菜单组件"""
        
        component_template = '''import React, { useState, useEffect } from 'react';
import { Menu } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import * as Icons from '@ant-design/icons';

interface MenuItemType {
  id: number;
  name: string;
  path: string;
  children: MenuItemType[] | string[];
  icon?: string;
}

interface MenuComponentProps {
  menuData: MenuItemType[];
  collapsed?: boolean;
}

const MenuComponent: React.FC<MenuComponentProps> = ({ menuData, collapsed = false }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);

  useEffect(() => {
    setSelectedKeys([location.pathname]);
  }, [location.pathname]);

  const getIcon = (menuName: string) => {
    const iconMap: Record<string, React.ComponentType> = {
      '移动执法': Icons.MobileOutlined,
      '污染源档案': Icons.FolderOpenOutlined,
      '企业环境健康码': Icons.QrcodeOutlined,
      '秸秆网格化管理': Icons.AppstoreOutlined,
      '装备调度': Icons.ToolOutlined,
      '系统管理': Icons.SettingOutlined,
    };
    
    const IconComponent = iconMap[menuName] || Icons.MenuOutlined;
    return React.createElement(IconComponent);
  };

  const renderMenuItem = (item: MenuItemType): React.ReactNode => {
    const hasObjectChildren = item.children && 
      item.children.length > 0 && 
      typeof item.children[0] === 'object';
    
    const hasStringChildren = item.children && 
      item.children.length > 0 && 
      typeof item.children[0] === 'string';

    if (hasObjectChildren) {
      return (
        <Menu.SubMenu
          key={item.id}
          icon={getIcon(item.name)}
          title={item.name}
        >
          {(item.children as MenuItemType[]).map(child => renderMenuItem(child))}
        </Menu.SubMenu>
      );
    }
    
    if (hasStringChildren) {
      return (
        <Menu.SubMenu
          key={item.id}
          icon={getIcon(item.name)}
          title={item.name}
        >
          {(item.children as string[]).map((childName, index) => (
            <Menu.Item
              key={`${item.id}-${index}`}
              onClick={() => navigate(`${item.path}/${childName.toLowerCase()}`)}
            >
              {childName}
            </Menu.Item>
          ))}
        </Menu.SubMenu>
      );
    }

    return (
      <Menu.Item
        key={item.id}
        icon={getIcon(item.name)}
        onClick={() => item.path && navigate(item.path)}
      >
        {item.name}
      </Menu.Item>
    );
  };

  return (
    <Menu
      mode="inline"
      selectedKeys={selectedKeys}
      inlineCollapsed={collapsed}
      style={{ height: '100%', borderRight: 0 }}
    >
      {menuData.map(item => renderMenuItem(item))}
    </Menu>
  );
};

export default MenuComponent;'''

        return {
            'MenuComponent.tsx': component_template
        }
    
    def generate_vanilla_js_component(self, menu_data: Dict[str, Any]) -> str:
        """生成原生JavaScript菜单组件"""
        
        js_template = '''class MenuComponent {
  constructor(container, menuData, options = {}) {
    this.container = container;
    this.menuData = menuData;
    this.options = {
      collapsed: false,
      showIcons: true,
      theme: 'light',
      ...options
    };
    
    this.selectedPath = '';
    this.init();
  }
  
  init() {
    this.render();
    this.bindEvents();
  }
  
  getIcon(menuName) {
    const iconMap = {
      '移动执法': '📱',
      '污染源档案': '📁',
      '企业环境健康码': '🏷️',
      '秸秆网格化管理': '🔳',
      '装备调度': '🔧',
      '系统管理': '⚙️'
    };
    
    return iconMap[menuName] || '📄';
  }
  
  renderMenuItem(item, level = 0) {
    const hasObjectChildren = item.children && 
      item.children.length > 0 && 
      typeof item.children[0] === 'object';
    
    const hasStringChildren = item.children && 
      item.children.length > 0 && 
      typeof item.children[0] === 'string';
    
    let html = '';
    
    if (hasObjectChildren || hasStringChildren) {
      html += `
        <li class="menu-item menu-submenu" data-id="${item.id}">
          <div class="menu-title" style="padding-left: ${level * 20}px">
            ${this.options.showIcons ? `<span class="menu-icon">${this.getIcon(item.name)}</span>` : ''}
            <span class="menu-text">${item.name}</span>
            <span class="menu-arrow">▶</span>
          </div>
          <ul class="submenu">
      `;
      
      if (hasObjectChildren) {
        item.children.forEach(child => {
          html += this.renderMenuItem(child, level + 1);
        });
      } else {
        item.children.forEach((childName, index) => {
          html += `
            <li class="menu-item" data-path="${item.path}/${childName.toLowerCase()}">
              <div class="menu-title" style="padding-left: ${(level + 1) * 20}px">
                <span class="menu-text">${childName}</span>
              </div>
            </li>
          `;
        });
      }
      
      html += '</ul></li>';
    } else {
      html += `
        <li class="menu-item" data-id="${item.id}" data-path="${item.path}">
          <div class="menu-title" style="padding-left: ${level * 20}px">
            ${this.options.showIcons ? `<span class="menu-icon">${this.getIcon(item.name)}</span>` : ''}
            <span class="menu-text">${item.name}</span>
          </div>
        </li>
      `;
    }
    
    return html;
  }
  
  render() {
    let html = '<ul class="menu-container">';
    
    this.menuData.forEach(item => {
      html += this.renderMenuItem(item);
    });
    
    html += '</ul>';
    
    this.container.innerHTML = html;
  }
  
  bindEvents() {
    this.container.addEventListener('click', (e) => {
      const menuItem = e.target.closest('.menu-item');
      if (!menuItem) return;
      
      const path = menuItem.dataset.path;
      const isSubmenu = menuItem.classList.contains('menu-submenu');
      
      if (isSubmenu) {
        // 切换子菜单显示/隐藏
        const submenu = menuItem.querySelector('.submenu');
        const arrow = menuItem.querySelector('.menu-arrow');
        
        if (submenu.style.display === 'none' || !submenu.style.display) {
          submenu.style.display = 'block';
          arrow.textContent = '▼';
        } else {
          submenu.style.display = 'none';
          arrow.textContent = '▶';
        }
      } else if (path && path !== '#') {
        // 处理路由跳转
        this.selectMenuItem(path);
        this.onMenuSelect && this.onMenuSelect(path);
      }
    });
  }
  
  selectMenuItem(path) {
    // 移除之前的选中状态
    this.container.querySelectorAll('.menu-item.selected').forEach(item => {
      item.classList.remove('selected');
    });
    
    // 添加新的选中状态
    const targetItem = this.container.querySelector(`[data-path="${path}"]`);
    if (targetItem) {
      targetItem.classList.add('selected');
    }
    
    this.selectedPath = path;
  }
  
  // 设置菜单选择回调
  onSelect(callback) {
    this.onMenuSelect = callback;
  }
}

// CSS样式
const menuStyles = `
.menu-container {
  list-style: none;
  padding: 0;
  margin: 0;
  background: #fff;
  border-right: 1px solid #e6e6e6;
  height: 100%;
  overflow-y: auto;
}

.menu-item {
  cursor: pointer;
  border-bottom: 1px solid #f5f5f5;
}

.menu-item:hover {
  background-color: #f5f5f5;
}

.menu-item.selected {
  background-color: #e6f7ff;
  border-right: 3px solid #1890ff;
}

.menu-title {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  font-size: 14px;
  color: #333;
}

.menu-icon {
  margin-right: 8px;
  font-size: 16px;
}

.menu-text {
  flex: 1;
}

.menu-arrow {
  font-size: 12px;
  transition: transform 0.3s;
}

.submenu {
  list-style: none;
  padding: 0;
  margin: 0;
  display: none;
  background-color: #fafafa;
}

.submenu .menu-item {
  border-bottom: none;
}

.submenu .menu-title {
  font-size: 13px;
  color: #666;
}
`;

// 注入样式
if (!document.getElementById('menu-styles')) {
  const styleSheet = document.createElement('style');
  styleSheet.id = 'menu-styles';
  styleSheet.textContent = menuStyles;
  document.head.appendChild(styleSheet);
}

// 导出
if (typeof module !== 'undefined' && module.exports) {
  module.exports = MenuComponent;
} else if (typeof window !== 'undefined') {
  window.MenuComponent = MenuComponent;
}'''

        return {
            'MenuComponent.js': js_template
        }
    
    def generate_route_config(self, menu_data: Dict[str, Any]) -> str:
        """生成路由配置"""
        if self.config.framework == FrameworkType.VUE_ELEMENT:
            return self._generate_vue_routes(menu_data)
        elif self.config.framework == FrameworkType.REACT_ANTD:
            return self._generate_react_routes(menu_data)
        else:
            return ""
    
    def _generate_vue_routes(self, menu_data: Dict[str, Any]) -> str:
        """生成Vue路由配置"""
        routes = []
        
        def extract_routes(items, parent_path=""):
            for item in items:
                if isinstance(item, dict):
                    path = item.get('path', '')
                    if path:
                        route = {
                            'path': path,
                            'name': item.get('name', ''),
                            'component': f"() => import('@/views{path}/index.vue')"
                        }
                        routes.append(route)
                    
                    if 'children' in item and item['children']:
                        if isinstance(item['children'][0], dict):
                            extract_routes(item['children'], path)
        
        # 处理菜单组
        if 'groups' in menu_data:
            for group in menu_data['groups']:
                extract_routes(group)
        
        route_config = "import { RouteRecordRaw } from 'vue-router'\n\n"
        route_config += "const routes: RouteRecordRaw[] = [\n"
        
        for route in routes:
            route_config += f"  {{\n"
            route_config += f"    path: '{route['path']}',\n"
            route_config += f"    name: '{route['name']}',\n"
            route_config += f"    component: {route['component']}\n"
            route_config += f"  }},\n"
        
        route_config += "]\n\nexport default routes"
        
        return route_config
    
    def _generate_react_routes(self, menu_data: Dict[str, Any]) -> str:
        """生成React路由配置"""
        routes = []
        
        def extract_routes(items):
            for item in items:
                if isinstance(item, dict):
                    path = item.get('path', '')
                    if path:
                        component_name = self._path_to_component_name(path)
                        routes.append({
                            'path': path,
                            'component': component_name
                        })
                    
                    if 'children' in item and item['children']:
                        if isinstance(item['children'][0], dict):
                            extract_routes(item['children'])
        
        if 'groups' in menu_data:
            for group in menu_data['groups']:
                extract_routes(group)
        
        route_config = "import { Routes, Route } from 'react-router-dom';\n"
        
        # 生成import语句
        for route in routes:
            route_config += f"import {route['component']} from './pages{route['path']}';\n"
        
        route_config += "\nconst AppRoutes = () => {\n"
        route_config += "  return (\n"
        route_config += "    <Routes>\n"
        
        for route in routes:
            route_config += f"      <Route path=\"{route['path']}\" element={{<{route['component']} />}} />\n"
        
        route_config += "    </Routes>\n"
        route_config += "  );\n"
        route_config += "};\n\n"
        route_config += "export default AppRoutes;"
        
        return route_config
    
    def generate_enhanced_vue_router(self, menu_data: Dict[str, Any]) -> str:
        """基于菜单数据和路由数据生成增强的Vue Router配置"""
        routes = menu_data.get('routes', [])
        
        router_imports = []
        route_definitions = []
        
        # 处理路由定义
        for route in routes:
            component_path = route['component']
            component_name = route['componentName']
            
            # 生成import语句
            router_imports.append(f"const {component_name} = () => import('{component_path}')")
            
            # 生成路由定义
            route_def = f"""  {{
    path: '{route['path']}',
    name: '{route['name']}',
    component: {component_name},
    meta: {{
      title: '{route['name']}',
      requiresAuth: true
    }}
  }}"""
            route_definitions.append(route_def)
        
        # 生成完整的路由配置
        router_config = f"""import {{ createRouter, createWebHistory }} from 'vue-router'

// 路由组件懒加载
{chr(10).join(router_imports)}

const routes = [
  {{
    path: '/',
    redirect: '/dashboard'
  }},
  {{
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/Dashboard.vue'),
    meta: {{
      title: '仪表盘',
      requiresAuth: true
    }}
  }},
{chr(10).join(route_definitions)}
]

const router = createRouter({{
  history: createWebHistory(),
  routes
}})

// 路由守卫
router.beforeEach((to, from, next) => {{
  const token = localStorage.getItem('token')
  
  if (to.meta.requiresAuth && !token) {{
    next('/login')
  }} else {{
    next()
  }}
}})

export default router"""
        
        return router_config
    
    def generate_menu_data_with_routes(self, menu_data: Dict[str, Any]) -> str:
        """生成包含路由信息的菜单数据文件"""
        routes = menu_data.get('routes', [])
        menu_groups = menu_data.get('groups', [])
        
        # 创建路由映射
        route_map = {route['path']: route for route in routes}
        
        # 增强菜单数据
        enhanced_menu_groups = []
        for group in menu_groups:
            enhanced_group = self.match_routes_to_menu(group, routes)
            enhanced_menu_groups.append(enhanced_group)
        
        # 生成TypeScript菜单数据文件
        menu_data_ts = f"""// 菜单数据类型定义
export interface MenuItem {{
  id: number;
  name: string;
  path: string;
  children: MenuItem[] | string[];
  icon?: string;
  route?: {{
    path: string;
    name: string;
    component: string;
    componentName: string;
  }};
}}

// 路由信息
export const routeData = {json.dumps(routes, ensure_ascii=False, indent=2)};

// 菜单组数据
export const menuGroups: MenuItem[][] = {json.dumps(enhanced_menu_groups, ensure_ascii=False, indent=2)};

// 获取指定菜单组
export const getMenuGroup = (groupIndex: number): MenuItem[] => {{
  return menuGroups[groupIndex] || [];
}};

// 根据路径查找菜单项
export const findMenuByPath = (path: string): MenuItem | null => {{
  for (const group of menuGroups) {{
    for (const item of group) {{
      const found = findMenuItemByPath(item, path);
      if (found) return found;
    }}
  }}
  return null;
}};

function findMenuItemByPath(item: MenuItem, path: string): MenuItem | null {{
  if (item.path === path) return item;
  
  if (item.children && Array.isArray(item.children)) {{
    for (const child of item.children) {{
      if (typeof child === 'object') {{
        const found = findMenuItemByPath(child as MenuItem, path);
        if (found) return found;
      }}
    }}
  }}
  
  return null;
}}"""
        
        return menu_data_ts
    
    def _path_to_component_name(self, path: str) -> str:
        """将路径转换为组件名"""
        parts = path.strip('/').split('/')
        return ''.join(word.capitalize() for word in parts if word)
    
    def generate_complete_project(self, data_dir: str, output_dir: str):
        """生成完整的前端项目文件（增强版 - 集成路由数据）"""
        print(f"🚀 开始生成{self.config.framework.value}项目...")
        
        # 加载菜单数据和路由数据
        menu_data = self.load_menu_data(data_dir)
        
        # 创建输出目录
        os.makedirs(output_dir, exist_ok=True)
        
        # 生成组件文件
        if self.config.framework == FrameworkType.VUE_ELEMENT:
            components = self.generate_vue_element_component(menu_data)
        elif self.config.framework == FrameworkType.REACT_ANTD:
            components = self.generate_react_antd_component(menu_data)
        elif self.config.framework == FrameworkType.VANILLA_JS:
            components = self.generate_vanilla_js_component(menu_data)
        else:
            components = {}
        
        # 保存组件文件
        for filename, content in components.items():
            file_path = os.path.join(output_dir, filename)
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"✅ 生成组件: {filename}")
        
        # 生成增强的路由配置（基于实际路由数据）
        if self.config.framework == FrameworkType.VUE_ELEMENT and 'routes' in menu_data:
            # 生成增强的Vue Router配置
            enhanced_router = self.generate_enhanced_vue_router(menu_data)
            router_path = os.path.join(output_dir, "router.ts")
            with open(router_path, 'w', encoding='utf-8') as f:
                f.write(enhanced_router)
            print(f"✅ 生成增强路由配置: router.ts")
        else:
            # 回退到基础路由配置
            route_config = self.generate_route_config(menu_data)
            route_filename = "routes.ts" if self.config.framework == FrameworkType.VUE_ELEMENT else "routes.tsx"
            route_path = os.path.join(output_dir, route_filename)
            
            with open(route_path, 'w', encoding='utf-8') as f:
                f.write(route_config)
            print(f"✅ 生成基础路由配置: {route_filename}")
        
        # 生成增强的菜单数据文件（包含路由信息）
        if 'routes' in menu_data:
            menu_data_ts = self.generate_menu_data_with_routes(menu_data)
            menu_data_path = os.path.join(output_dir, "menuData.ts")
            with open(menu_data_path, 'w', encoding='utf-8') as f:
                f.write(menu_data_ts)
            print(f"✅ 生成增强菜单数据: menuData.ts")
        
        # 生成基础菜单数据JSON（兼容性）
        menu_data_json_path = os.path.join(output_dir, "menuData.json")
        with open(menu_data_json_path, 'w', encoding='utf-8') as f:
            json.dump(menu_data.get('groups', []), f, ensure_ascii=False, indent=2)
        print(f"✅ 生成菜单数据JSON: menuData.json")
        
        # 生成README文档
        readme_content = self.generate_readme(menu_data)
        readme_path = os.path.join(output_dir, "README.md")
        with open(readme_path, 'w', encoding='utf-8') as f:
            f.write(readme_content)
        print(f"✅ 生成项目文档: README.md")
        
        print(f"🎉 项目生成完成! 输出目录: {output_dir}")
        
        # 输出统计信息
        if 'routes' in menu_data:
            print(f"📊 统计信息:")
            print(f"  - 路由数量: {len(menu_data['routes'])}")
            print(f"  - 菜单组数量: {len(menu_data.get('groups', []))}")
            total_menu_items = sum(len(group) for group in menu_data.get('groups', []))
            print(f"  - 菜单项总数: {total_menu_items}")
    
    def generate_readme(self, menu_data: Dict[str, Any]) -> str:
        """生成项目README文档"""
        framework_name = {
            FrameworkType.VUE_ELEMENT: "Vue 3 + Element Plus",
            FrameworkType.REACT_ANTD: "React + Ant Design",
            FrameworkType.VANILLA_JS: "Vanilla JavaScript"
        }.get(self.config.framework, "Unknown")
        
        routes_count = len(menu_data.get('routes', []))
        menu_groups_count = len(menu_data.get('groups', []))
        
        readme = f"""# 自动生成的前端菜单项目

## 项目信息

- **框架**: {framework_name}
- **生成时间**: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
- **路由数量**: {routes_count} 个
- **菜单组数量**: {menu_groups_count} 个

## 文件结构

```
.
├── README.md              # 项目说明文档
├── menuData.json          # 菜单数据（JSON格式）
├── menuData.ts            # 菜单数据（TypeScript格式，包含路由信息）
├── router.ts              # 路由配置文件
├── MenuComponent.vue      # 主菜单组件
└── MenuItem.vue           # 菜单项组件
```

## 使用方法

### 1. 安装依赖

```bash
npm install {self._get_dependencies()}
```

### 2. 导入菜单组件

```typescript
import MenuComponent from './MenuComponent.vue'
import {{ menuGroups }} from './menuData'

// 在组件中使用
export default {{
  components: {{
    MenuComponent
  }},
  setup() {{
    return {{
      menuData: menuGroups[0] // 使用第一个菜单组
    }}
  }}
}}
```

### 3. 配置路由

```typescript
import router from './router'

// 在main.ts中使用
app.use(router)
```

## 菜单数据结构

```typescript
interface MenuItem {{
  id: number;
  name: string;
  path: string;
  children: MenuItem[] | string[];
  icon?: string;
  route?: {{
    path: string;
    name: string;
    component: string;
    componentName: string;
  }};
}}
```

## 特性

- ✅ 支持多级菜单（最多5级）
- ✅ 支持菜单图标
- ✅ 支持菜单折叠
- ✅ 自动路由匹配
- ✅ TypeScript支持
- ✅ 响应式设计

## 自定义

### 修改图标

在 `MenuComponent.vue` 中的 `getMenuIcon` 方法中添加自定义图标映射。

### 修改样式

在 `MenuComponent.vue` 的 `<style>` 部分修改样式。

### 添加权限控制

在路由守卫中添加权限验证逻辑。

---

*此项目由菜单生成Agent自动生成*
"""
        return readme
    
    def _get_dependencies(self) -> str:
        """获取框架依赖"""
        deps = {
            FrameworkType.VUE_ELEMENT: "vue@^3.0.0 vue-router@^4.0.0 element-plus@^2.0.0",
            FrameworkType.REACT_ANTD: "react@^18.0.0 react-router-dom@^6.0.0 antd@^5.0.0",
            FrameworkType.VANILLA_JS: ""
        }
        return deps.get(self.config.framework, "")
    
    def _generate_readme(self, menu_data: Dict[str, Any]) -> str:
        """生成项目说明文档"""
        framework_name = {
            FrameworkType.VUE_ELEMENT: "Vue 3 + Element Plus",
            FrameworkType.REACT_ANTD: "React + Ant Design", 
            FrameworkType.VANILLA_JS: "原生 JavaScript"
        }[self.config.framework]
        
        return f"""# {framework_name} 菜单组件

## 自动生成说明

此项目由前端菜单生成Agent自动生成，基于以下配置：

- **框架**: {framework_name}
- **组件名**: {self.config.component_name}
- **图标支持**: {'✅' if self.config.enable_icons else '❌'}
- **权限控制**: {'✅' if self.config.enable_permissions else '❌'}
- **折叠支持**: {'✅' if self.config.collapse_support else '❌'}

## 菜单结构统计

- **一级菜单**: {len(menu_data.get('first_level', []))} 个
- **菜单组数**: {len(menu_data.get('groups', []))} 个

## 使用方法

### 1. 安装依赖

```bash
npm install
```

### 2. 引入组件

```javascript
import MenuComponent from './MenuComponent'
```

### 3. 使用组件

```javascript
<MenuComponent menuData={{menuData}} />
```

## 文件说明

- `MenuComponent.*`: 主菜单组件
- `MenuItem.*`: 菜单项子组件（如适用）
- `routes.*`: 路由配置文件
- `menuData.json`: 菜单数据文件

## 自定义配置

你可以通过修改组件props来自定义菜单行为：

- `collapsed`: 是否折叠菜单
- `theme`: 主题样式
- `showIcons`: 是否显示图标

## 注意事项

1. 确保已安装相应的UI框架依赖
2. 图标组件需要单独安装和配置
3. 路由配置需要根据实际项目结构调整

---

*由前端菜单生成Agent自动生成 @ {self.config.framework.value}*
"""

# 使用示例
if __name__ == "__main__":
    # 创建配置
    config = MenuGenerationConfig(
        framework=FrameworkType.VUE_ELEMENT,
        output_dir="generated_menu",
        enable_icons=True,
        collapse_support=True
    )
    
    # 创建Agent并生成项目
    agent = MenuAgent(config)
    agent.generate_complete_project("data", "generated_menu/vue")
    
    print("\\n" + "="*50)
    print("🎯 菜单生成Agent使用说明:")
    print("1. 修改配置选择不同框架")
    print("2. 自定义图标映射规则") 
    print("3. 添加权限控制逻辑")
    print("4. 扩展主题和样式支持")
    print("="*50)
